<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\ScenicProduct;
use plugin\ky_black\app\admin\model\ProductCategory;
use plugin\ky_black\app\admin\model\BusinessPartner;
use support\Db;
use plugin\ky_black\app\admin\model\BusinessType;

class ScenicProductController extends BaseController
{
    /**
     * 获取产品列表
     */
    public function list(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 15);
        
        $query = ScenicProduct::with(['category', 'scenicSpot']);
        
        // 名称搜索
        if ($name = $request->input('params.name')) {
            $query->where('name', 'like', "%{$name}%");
        }
        
        // 分类筛选
        if ($categoryId = $request->input('params.category_id')) {
            $query->where('category_id', $categoryId);
        }
        
        // 景区筛选
        if ($scenicSpotId = $request->input('params.scenic_spot_id')) {
            $query->where('scenic_spot_id', $scenicSpotId);
        }
        
        // 状态筛选
        $status = $request->input('params.status');
        if (null !== $status && $status !== '') {
            $query->where('status', $status);
        }
        
        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('sort', 'desc')
                      ->orderBy('product_id', 'desc')
                      ->get();
            
        return $this->success([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 获取选项数据
     */
    public function options(): Response
    {
        // 获取景区类型的ID
        $scenicTypeId = BusinessType::where('code', 'scenic')->value('id');

        return $this->success([
            'categories' => ProductCategory::where('status', 1)
                ->orderBy('sort', 'desc')
                ->get(['category_id', 'name', 'parent_id']),
            'scenic_spots' => BusinessPartner::where('status', 1)
                ->where('business_type_id', $scenicTypeId)
                ->orderBy('sort', 'desc')
                ->get(['partner_id as scenic_spot_id', 'name']),
            'product_types' => [
                'package' => '套餐',
                'single' => '单品',
                'service' => '服务'
            ]
        ]);
    }

    /**
     * 添加产品
     */
    public function add(Request $request): Response
    {
        $data = $request->post();
        
        // 处理 category_id，如果是数组，取最后一个值
        if (isset($data['category_id']) && is_array($data['category_id'])) {
            $data['category_id'] = end($data['category_id']);
        }
        
        // 处理 images 字段
        if (!isset($data['images'])) {
            $data['images'] = [];
        } elseif (!is_array($data['images'])) {
            $data['images'] = [$data['images']];
        }
        
        // 确保数字字段为整数
        $intFields = ['category_id', 'scenic_spot_id', 'validity_period', 'min_people', 'max_people', 'sort', 'status', 'is_featured'];
        foreach ($intFields as $field) {
            if (isset($data[$field]) && $data[$field] !== null) {
                $data[$field] = (int)$data[$field];
            }
        }
        
        // 确保价格字段为浮点数
        $floatFields = ['price', 'black_card_price', 'original_price'];
        foreach ($floatFields as $field) {
            if (isset($data[$field])) {
                $data[$field] = (float)$data[$field];
            }
        }
        
        // 生成产品编码
        $prefix = strtoupper(substr($data['type'], 0, 1)); // 根据类型生成前缀：S(single), P(package), V(service)
        $date = date('Ymd');
        $randomNum = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $data['code'] = $prefix . $date . $randomNum;
        
        // 开启事务
        Db::beginTransaction();
        try {
            // 检查编码是否已存在
            while (ScenicProduct::where('code', $data['code'])->exists()) {
                $randomNum = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
                $data['code'] = $prefix . $date . $randomNum;
            }
            
            // 保存产品基本信息
            $product = new ScenicProduct();
            $product->fill($data);
            $product->save();

            Db::commit();
            return $this->success(['product_id' => $product->product_id], '添加成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑产品
     */
    public function edit(Request $request): Response
    {
        $data = $request->post();
        
        // 处理 category_id，如果是数组，取最后一个值
        if (isset($data['category_id']) && is_array($data['category_id'])) {
            $data['category_id'] = end($data['category_id']);
        }
        
        // 处理 images 字段
        if (!isset($data['images'])) {
            $data['images'] = [];
        } elseif (!is_array($data['images'])) {
            $data['images'] = [$data['images']];
        }
        
        // 确保数字字段为整数
        $intFields = ['category_id', 'scenic_spot_id', 'validity_period', 'min_people', 'max_people', 'sort', 'status', 'is_featured'];
        foreach ($intFields as $field) {
            if (isset($data[$field]) && $data[$field] !== null) {
                $data[$field] = (int)$data[$field];
            }
        }
        
        // 确保价格字段为浮点数
        $floatFields = ['price', 'black_card_price', 'original_price'];
        foreach ($floatFields as $field) {
            if (isset($data[$field])) {
                $data[$field] = (float)$data[$field];
            }
        }
        
        $product = ScenicProduct::find($data['product_id']);
        if (!$product) {
            return $this->error('产品不存在');
        }

        // 开启事务
        Db::beginTransaction();
        try {
            // 防止修改产品编码
            unset($data['code']);
            
            // 更新产品基本信息
            $product->fill($data);
            $product->save();

            Db::commit();
            return $this->success(['product_id' => $product->product_id], '编辑成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error('编辑失败：' . $e->getMessage());
        }
    }

    /**
     * 删除产品
     */
    public function delete(Request $request): Response
    {
        $productId = $request->input('product_id');
        $product = ScenicProduct::find($productId);
        if (!$product) {
            return $this->error('产品不存在');
        }

        if ($product->delete()) {
            return $this->success(null, '删除成功');
        }
        return $this->error('删除失败');
    }

    /**
     * 更新产品状态
     */
    public function status(Request $request): Response
    {
        $productId = $request->input('product_id');
        $status = (int)$request->input('status');

        $product = ScenicProduct::find($productId);
        if (!$product) {
            return $this->error('产品不存在');
        }
        
        $product->status = $status;
        if ($product->save()) {
            return $this->success(null, '状态更新成功');
        }
        return $this->error('状态更新失败');
    }

    /**
     * 获取产品详情
     */
    public function detail(Request $request): Response
    {
        $productId = $request->input('product_id');
        if (!$productId) {
            return $this->error('参数错误');
        }

        $product = ScenicProduct::with(['category', 'scenicSpot'])->find($productId);
        if (!$product) {
            return $this->error('产品不存在');
        }

        return $this->success($product);
    }
}